package com.woniuxy.search.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.api.StuApi;
import com.woniuxy.common.model.dto.PageDto;
import com.woniuxy.common.result.Result;
import com.woniuxy.search.model.entity.Stu;
import com.woniuxy.search.service.SearchService;
import com.woniuxy.search.service.StuService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/es")
@Slf4j
public class SearchController {
    @Autowired
    private SearchService searchService;
    @Autowired
    private StuService stuService;
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @PostMapping("/save")
    @ApiOperation("批量保存到 Elasticsearch")
    public Result<String> save() {
        List<Stu> list = stuService.list();
        try {
            elasticsearchRestTemplate.save(list);
            return Result.ok("数据已成功保存到 Elasticsearch");
        } catch (Exception e) {
            log.error("保存数据到 Elasticsearch 失败", e);
            return Result.fail("保存到 Elasticsearch 失败：" + e.getMessage());
        }
    }

    @PostMapping("/search")
    @ApiOperation("通过 info 字段分页搜索学生")
    public Result<Page<Stu>> search(@RequestBody PageDto pageDto) {
        Page<Stu> resultPage = searchService.search(pageDto);  // 调用服务层方法
        return Result.ok(resultPage);
    }

    @PostMapping("/remove")
    @ApiOperation("删除指定 id 的学生")
    public Result<String> remove(int id) {
        try {
            // 创建查询，匹配 ID
            Query query = new NativeSearchQueryBuilder()
                    .withQuery(QueryBuilders.termQuery("sno", id)) // 通过 id 字段查询
                    .build();

            // 使用 query 删除文档
            elasticsearchRestTemplate.delete(query, Stu.class, IndexCoordinates.of("stu"));

            return Result.ok("删除成功");
        } catch (Exception e) {
            log.error("删除数据到 Elasticsearch 失败", e);
        }
        return Result.fail("删除失败");
    }





}